package com.guoxin.chapter1;


/**
 * 共享数据的Thread
 *
 * @author guoxin
 * @date 2019/8/8
 */
public class SharedDataThread {
    private static int count = 5;

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        new Thread(myThread, "T1").start();
        new Thread(myThread, "T2").start();
        new Thread(myThread, "T3").start();
        new Thread(myThread, "T4").start();
        new Thread(myThread, "T5").start();
    }

    /**
     * 非线程安全主要是指多个线程对同一对象中的同一个实例变量进行操作时会出现值别更改、值不同步的情况，进而影响程序的执行流程
     */
    public static class MyThread implements Runnable {

        @Override
        public void run() {
            count--;
            System.out.println("由 " + Thread.currentThread().getName() + " 计算的结果为：" + count);
        }
    }


    public static class MyThread2 implements Runnable {

        /**
         * synchronized 可以在任意对象或方法上加锁，而加锁的这段代码称为“互斥区”或“临界区”
         */
        @Override
        public synchronized void run() {
            count--;
            System.out.println("由 " + Thread.currentThread().getName() + " 计算的结果为：" + count);
        }
    }
}
